import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Login from './pages/Login';
import Study from './pages/Study';
import BookSelection from './pages/BookSelection';
import ErrorPage from './pages/ErrorPage'; // 确保这一行是正确的
import './style.css'; // 导入样式

// 在这里定义 API_BASE，使其在整个文件（包括 ProtectedRoute）中可用
// 确保这里没有 /api
const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8000'; 

interface ProtectedRouteProps {
  children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);

  useEffect(() => {
    const checkAuth = async () => {
      const token = localStorage.getItem('token');
      if (token) {
        try {
          // 调用后端 /user/me 接口验证 token 有效性
          const response = await fetch(`${API_BASE}/user/me`, {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          });
          const result = await response.json();
          // 检查后端返回的 code
          if (result.code === 200) {
            setIsAuthenticated(true);
          } else {
            // Token无效或过期，清除并标记为未认证
            console.error("验证用户失败:", result.msg || "未知错误");
            localStorage.removeItem('token');
            setIsAuthenticated(false);
          }
        } catch (error) {
          console.error("验证用户请求失败:", error);
          localStorage.removeItem('token');
          setIsAuthenticated(false);
        }
      } else {
        // 没有 token，标记为未认证
        setIsAuthenticated(false);
      }
    };

    checkAuth();
  }, []); // 确保依赖数组为空，只在组件挂载时运行一次

  if (isAuthenticated === null) {
    // 仍在检查认证状态时显示加载中...
    return <div className="loading">加载认证状态...</div>;
  }

  if (!isAuthenticated) {
    // 未认证，重定向到登录页面
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
};

const App: React.FC = () => {
  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/books" element={
          <ProtectedRoute>
            <BookSelection />
          </ProtectedRoute>
        } />
        <Route path="/study" element={
          <ProtectedRoute>
            <Study />
          </ProtectedRoute>
        } />
        {/* 根路径默认重定向到登录页 */}
        <Route path="/" element={<Navigate to="/login" replace />} />
        {/* 404 页面 */}
        <Route path="*" element={<ErrorPage />} />
      </Routes>
    </Router>
  );
};

export default App; 